/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.task.support.scripting;

import cn.easyplatform.lang.Files;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.web.task.support.ScriptEngine;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.RhinoException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class EventScriptEngine implements ScriptEngine {

    private final static Logger log = LoggerFactory.getLogger(EventScriptEngine.class);

    private static String functions;

    static {
        StringBuilder sb = new StringBuilder();
        //InputStream is = EventScriptEngine.class.getResourceAsStream("cmd0.so");
        sb.append(Files.read("support/lib/cmd0.so"));
        //is = EventScriptEngine.class.getResourceAsStream("cmd1.so");
        sb.append(Files.read("support/lib/cmd1.so"));
        functions = sb.toString();
        sb = null;
    }

    private String script;

    private RhinoScriptable scope;

    @Override
    public void init(Map<String, Object> variables, String prefixScript,
                     String script) {
        String[] exprs = ScriptUtils.parse(script.trim());
        this.script = exprs[0];
        if (log.isDebugEnabled())
            log.debug("eval event:{}", this.script);
        Context cx = Context.enter();
        try {
            cx.setOptimizationLevel(-1);
            scope = new RhinoScriptable(variables, true);
            scope.initStandardObjects(cx, false);
            StringBuilder sb = new StringBuilder();
            if (exprs.length > 1) {
                for (int i = 1; i < exprs.length; i++)
                    sb.append(exprs[i]).append("\n");
            }
            sb.append(functions);
            if (!Strings.isBlank(prefixScript)) {
                exprs = ScriptUtils.parse(prefixScript.trim());
                for (int i = 0; i < exprs.length; i++)
                    sb.append(exprs[i]).append("\n");
            }
            cx.evaluateString(scope, sb.toString(), "", 1, null);
            sb = null;
        } catch (RhinoException ex) {
            throw ScriptUtils.handleScriptException(ex);
        } finally {
            Context.exit();
        }
    }

    @Override
    public void eval(int line) {
        Context cx = Context.enter();
        try {
            cx.setOptimizationLevel(-1);
            cx.evaluateString(scope, this.script, "", line, null);
        } catch (RhinoException ex) {
            throw ScriptUtils.handleScriptException(ex);
        } finally {
            Context.exit();
        }
    }

    @Override
    public void destory() {
        if (scope != null) {
            scope.clear();
            scope = null;
        }
    }

}
